package com.xz.realdemo.util;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * @author 张志航     
 * @version V1.0.0
 * @projectName design_mode
 * @title     XMLUtil   
 * @package    com.xz.example.util  
 * @date   2019/11/26 19:15  
 * @explain
 */
public class XMLUtil {

    public static Object getBean(){
        try {
            // 创建DOM文档对象
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = dFactory.newDocumentBuilder();
            Document doc = documentBuilder.parse(new File("AdapterPattern/src/com/xz/realdemo/config.xml"));

            // 获取配置bean
            NodeList nl = doc.getElementsByTagName("className");
            Node node = nl.item(0).getFirstChild();
            String clazzName = node.getNodeValue();

            // 利用反射生成对象并返回
            Object obj = Class.forName(clazzName).newInstance();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
